import cv2
import numpy as np
import imutils
import scipy.signal as signal
from scipy import ndimage
from matplotlib import pyplot as plt
from rect_detect import rectangle_detect

def grid_patch(img, patch_size, grid):
    # img = cv2.imread(imgpath)
    h, w, _ = img.shape
    img_patches = np.empty(((grid ** 2), patch_size, patch_size, 3), dtype=np.uint8)
    coord = np.empty(((grid ** 2), 4), dtype=np.int)
    x_endsteps = np.linspace(patch_size, w, num=grid)
    y_endsteps = np.linspace(patch_size, h, num=grid)

    for i, ystep in enumerate(y_endsteps):
        for j, xstep in enumerate(x_endsteps):
            xmax = int(xstep)
            ymax = int(ystep)
            xmin = int(xstep - patch_size)
            ymin = int(ystep - patch_size)

            patch_img = img[ymin:ymax, xmin:xmax, :]
            img_patches[i * grid + j, :, :, :] = patch_img
            coord[i * grid + j] = [xmin, ymin, xmax, ymax]

    return img_patches, coord  # [grid**2, H,W,BGR]

def isinrect(pa,pb,pc,pd,pm):
    ab = [pb[0]-pa[0],pb[1]-pa[1]]
    am = [pm[0] - pa[0], pm[1] - pa[1]]
    bc = [pc[0] - pb[0], pc[1] - pb[1]]
    bm = [pm[0] - pb[0], pm[1] - pb[1]]
    cd = [pd[0] - pc[0], pd[1] - pc[1]]
    cm = [pm[0] - pc[0], pm[1] - pc[1]]
    da = [pa[0] - pd[0], pa[1] - pd[1]]
    dm = [pm[0] - pd[0], pm[1] - pd[1]]

    pro1 = ab[0]*am[1]-am[0]*ab[1]
    pro2 = bc[0] * bm[1] - bc[0] * bm[1]
    pro3 = cd[0] * cm[1] - cd[0] * cm[1]
    pro4 = da[0] * dm[1] - da[0] * dm[1]

    if pro1>0 and pro2>0 and pro3>0 and pro4>0:
        return 1
    else:
        return 0


img = cv2.imread("data/IMG_3846.JPG")
ori_img = img.copy()
print 'img shape',img.shape
whole_img = np.zeros((img.shape[0], img.shape[1]),np.uint8)
detect_result = rectangle_detect(img)

if not detect_result is None:

    corners,h2 = detect_result
    ss = np.zeros_like(h2, np.uint8)
    cv2.line(ss, corners[0], corners[1], (255,), 2)
    cv2.line(ss, corners[1], corners[2], (255,), 2)
    cv2.line(ss, corners[2], corners[3], (255,), 2)
    cv2.line(ss, corners[3], corners[0], (255,), 2)
    plt.figure()
    plt.imshow(ss)
    plt.show()

    _, screen, _= cv2.findContours(ss.copy(),mode=cv2.RETR_TREE ,method=cv2.CHAIN_APPROX_SIMPLE)
    screen = sorted(screen, key=cv2.contourArea,reverse=True)[:1]
    cv2.fillConvexPoly(ss, screen[0], 1)
    ss = imutils.resize(ss,height=img.shape[0],width=img.shape[1])
    print ss.max()
    plt.figure()
    plt.imshow(ss)
    plt.show()


    img_midfilt = ndimage.median_filter(img, 2)
    gray_ori = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_filt = cv2.cvtColor(img_midfilt, cv2.COLOR_BGR2GRAY)
    canny =cv2.Canny(gray_filt,70,70*3)
    canny[ss==0]=0



    kernel_d = np.array([[0,1,0],
                         [1,1,1],
                         [0,1,0]
                         ]).astype(np.uint8)
    dilated = cv2.dilate(canny, kernel_d)



    labeled_img = img.copy()
    _, contours, hierarchy= cv2.findContours(dilated,mode=cv2.RETR_TREE ,method=cv2.CHAIN_APPROX_SIMPLE)

    ones = np.zeros_like(dilated, np.uint8)
    huahen=[]
    i = 0

    for c in contours:
        i+=1
        a = cv2.contourArea(c)
        p = cv2.arcLength(c, True)
        r = (p-10)*0.5*5 / a
        if a>500 and a<50000:
            huahen.append(c)
            x, y, w, h = cv2.boundingRect(c)
            cv2.rectangle(ori_img, (x, y), (x + w, y + h), (0, 255, 0), 5)
            cv2.putText(ori_img, '%d, %.2f'%(p*0.5, r), (x, y),cv2.FONT_HERSHEY_COMPLEX,
                        1, (0, 255, 0), 2)

            # isinrect(pa=)

    cv2.drawContours(ones, huahen, -1, (1,), 1)

    whole_img= ones



    plt.figure(figsize=(15,8))
    plt.subplots_adjust(top=0.95,bottom=0.05,left=0.05,right=0.95,hspace=0.15, wspace=0.01)
    plt.subplot(221)
    plt.title('img')
    plt.imshow(img)

    plt.subplot(222)
    plt.title('whole_img')
    plt.imshow(whole_img)

    plt.subplot(223)
    plt.title('ori_img')
    plt.imshow(ori_img)


    plt.show()